<?php
	$airmonths = array("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
	$oldmovie = "";
	$olddir = "";
	$tvxml = "";
	$imdbnr = 0;
	$movtypes = array("mov","avi","mpg","mpeg","divx","ogm","mkv","mp4","m4v","mp4v");
//	$file = "Battlestar.Galactica.S1.E10.The.Hand.of.God.DVDRip.Divx";
//	$file = "heroes.121.hdtv-lol.avi";
//	$file = "Megas XLR - 2x06 Space Booty [Moonsong].avi";

	$language = array();
	$data = file(str_replace("series_process.php","srtlanguages.txt",$argv[0]));
	foreach($data as $line){
		$temp = explode("\t",$line);
		$language[trim($temp[2])] = array("series"=>$temp[0],"movies"=>$temp[1]);
	}
	$thelanguage = $language[$argv[4]]["series"];



	if(isset($argv[1]) and file_exists($argv[1])){
		$moviedir = substr($argv[1], 0, strrpos($argv[1],"/")+1);
		$file = substr($argv[1],strrpos($argv[1],"/")+1);

		processfile($moviedir, $file);
	}else{
		die("\nUsage: php series.php <path_to_movie> <download_subtitles 1|0>\n\n");
	}



	function processfile($dir, $file){
		global $airmonths, $oldmovie, $movtypes, $tvxml, $olddir, $imdbnr, $argv, $thelanguage;
			$ext = strtolower(substr($file, strrpos($file, ".")+1));

			$matches = array();
			if(preg_match("/(.+?)\Ds(\d+)\.?e(\d+?)\.(\D+)\./i", $file, $matches)){
//				echo "version 1...\n";
				$episode = round($matches[3]);
				$season  = round($matches[2]);
				$release = $matches[4];
				$title   = str_replace("."," ",$matches[1]);
			}elseif(preg_match("/(.+?)\Ds(\d+)\.?x(\d+?)\.(\D+)\./i", $file, $matches)){
//				echo "version 2...\n";
				$episode = round($matches[3]);
				$season  = round($matches[2]);
				$release = $matches[4];
				$title   = str_replace("."," ",$matches[1]);
			}elseif(preg_match("/(.+?)\D(\d+)x(\d+)\.(\D+)\./i", $file, $matches)){
//				echo "version 3...\n";
				$episode = round($matches[3]);
				$season  = round($matches[2]);
				$release = $matches[4];
				$title   = str_replace("."," ",$matches[1]);
			}elseif(preg_match("/(.+?)\D(\d+)\.(\D+)\./", $file, $matches)){
//				echo "version 5...\n";
//				print_r($matches);
				$episode = round(substr($matches[2],1));
				$season  = round(substr($matches[2],0,1));
				$release = $matches[3];
				$title   = str_replace("."," ",$matches[1]);
			}elseif(preg_match("/(\d+?) - ([\w\s]+) - /", $file, $matches)){
//				echo "version 6...\n";
				$episode = round(substr($matches[1],1));
				$season  = 1;
				$title   = str_replace("."," ",$matches[2]);
				$release = "none";
			}
			

			// Getting screenshot for episode... Getting them online, or create them ourselves...
			if((!file_exists($dir.str_replace(".".$ext,".jpg", $file))) and (!file_exists($dir.str_replace(".".$ext,".png", $file)))){
				// Make screenshot...
				if(file_exists($argv[2]."Contents/Resources/mplayer")){
						exec($argv[2].'Contents/Resources/mplayer -really-quiet -nosound -ss 720 -frames 1 -vf scale=400:-2 -vo png:z=1 "'.$dir.$file.'"');
						if(file_exists("00000001.png")){
							rename("00000001.png",$dir.str_replace(".".$ext,".png", $file));
						}
					echo $dir.str_replace(".".$ext,".png", $file);
				}
			}else{
				if(file_exists($dir.str_replace(".".$ext,".jpg", $file))){
					echo $dir.str_replace(".".$ext,".jpg", $file);
				}else{
					echo $dir.str_replace(".".$ext,".png", $file);
				}
			}



			if(!file_exists($dir.str_replace(".".$ext,".xml", $file)) and (!file_exists($dir."noxml.txt"))){
			
				$temp = get_show($title,0, $season."x".$episode);

				$title = substr($temp[5],strpos($temp[5], "\"")+1);
				$title = substr($title, 0, strpos($title, "\""));

				$airdate = explode("/",trim(substr($temp[5], strpos($temp[5], "aired on ")+10)));
				$airdate = $airdate[2]."-".array_search($airdate[1],$airmonths)."-".$airdate[0];

				$genres = explode(" | ",trim($temp[10]));

				if(isset($temp[6]) and ($temp[6] != "")){
					$episodepage = implode("",file($temp[6]));
					$episodeinfo = substr($episodepage, strpos($episodepage, "<td align='center'><font size='2'><b>Episode Summary</b></font></td>"), strpos($episodepage, "<td align='center'><font size='2'><b>Guest Stars</b></font></td>")-strpos($episodepage, "<td align='center'><font size='2'><b>Episode Summary</b></font></td>"));
					$episodeinfo = substr($episodeinfo, strpos($episodeinfo, "<table width='100%'><tr><td>")+strlen("<table width='100%'><tr><td>"));
					$episodeinfo = substr($episodeinfo, 0, strpos($episodeinfo, "</td>"));
					$episodeinfo = strip_tags($episodeinfo);
					$episodeinfo = trim(str_replace("&nbsp;"," ",$episodeinfo));
				}
				$screenshot  = substr($episodepage, strpos($episodepage, "http://images.tvrage.net/screencaps/"));
				$screenshot  = substr($screenshot, 0, strpos($screenshot, "\""));
				$screenshot  = strip_tags($screenshot);

				$publisher = trim($temp[11]);


				$movie = trim($temp[0]);


				if(file_exists($dir."seriestitle.txt")){	// Cached real title
					$temp	= file($subdirname."seriestitle.txt");
					$movie	= trim($temp[0]);
				}
				if(file_exists($dir."imdbnr.txt")){		// Cached IMDB nr
					$temp	= file($dir."imdbnr.txt");
					$imdbnr	= trim($temp[0]);
				}else{
					require_once("imdbsearch.class.php");
					$search = new imdbsearch();
					$search->setsearchname($movie);
					$results = $search->results();
					foreach ($results as $res) {
						if((strtolower($res->title()) == '&#34;'.strtolower($movie).'&#34;') or (strtolower($res->title()) == '"'.strtolower($movie).'"') or ($res->title() == "&nbsp;")){ // For some reason $res->title() is '&nbsp;' for series in our version of imdbphp...
							$imdbnr = $res->imdbid();
							break;
						}
					}	
					if($imdbnr > 0){
						$temp	= fopen($dir."imdbnr.txt","w");
						fwrite($temp, $imdbnr);
						$temp	= fopen($dir."seriestitle.txt","w");
						fwrite($temp, $movie);
					}
				}
				if(file_exists($dir."seriesbasexml.xml")){
					$tvxml = implode("",file($dir."seriesbasexml.xml"));
				}else{
					if($imdbnr > 0){
						require_once("imdbsearch.class.php");
						$movie = new imdb($imdbnr);
						$seriesID = $imdbnr;
						$movie->setid ($seriesID);
				
						$certs = $movie->mpaa();
						if(isset($certs["Belgium"])){ $tvxml .= '	<rating>'.$certs["Belgium"].' (Belgium)</rating>'."\n"; }
						elseif(isset($certs["USA"])){ $tvxml .= '	<rating>'.$certs["USA"].'</rating>'."\n"; }
						$tvxml .= '	<starRating>'.round($movie->rating()/2)."</starRating>\n	<published>".$movie->year()."-01-01</published>\n";
						$tvxml .= '	<genres>'."\n";
						$gen = $movie->genres ();
						$setgenres = array();
						$i=0;
						foreach($gen as $genre){
							if(in_array($genre, $setgenres)){ continue; }
							$tvxml .= '		<genre'.(($i==0)?' primary="true"':'').'>'.$genre.'</genre>'."\n";
							array_push($setgenres, $genre);
							$i++;
						}
						$tvxml .= "\t</genres>\n\t<cast>\n";
						$cast = $movie->cast();
						foreach($cast as $member){
							$tvxml .= '		<name>'.$member["name"].'</name>'."\n";
						}	
						$tvxml .= "\t</cast>\n\t<producers>\n";
						$cast = $movie->producer();
						foreach($cast as $member){
							$tvxml .= '		<name>'.$member["name"].'</name>'."\n";
						}
						$tvxml .= "\t</producers>\n\t<directors>\n";
						$cast = $movie->director();
						foreach($cast as $member){
							$tvxml .= '		<name>'.$member["name"].'</name>'."\n";
						}
						$tvxml .= "\t</directors>\n\t<authors>\n";
						$cast = $movie->writing();
						foreach($cast as $member){
							$tvxml .= '		<name>'.$member["name"].'</name>'."\n";
						}
						$tvxml .= "	</authors>\n";
				
				
						$basexml = fopen($dir."seriesbasexml.xml","w");
						fwrite($basexml, $tvxml);
						fclose($basexml);
					}else{
						$tvxml = "";
					}
				}

				$xml = '<media type="TV Show">
	<title>'.sprintf("%02s",$episode).". ".$title.'</title>
	<description>'.str_replace("\n\n","\n",$episodeinfo).'</description>
	<publisher>'.$publisher.'</publisher>
	<copyright>Copyright '.trim($temp[2]).' '.$publisher.'</copyright>
	<seriesName>'.trim($temp[0]).'</seriesName>
	<broadcaster>'.$publisher.'</broadcaster>
	<episodeNumber>'.$season.$episode.'</episodeNumber>
	<episode>'.$episode.'</episode>
	<season>'.$season.'</season>
	<published>'.$airdate.'</published>
'.$tvxml.'
</media>
';
		
		/*
			<acquired>2007-04-01</acquired>
			<artist>October Road</artist>
			<summary>The Pros and Cons of Upsetting the Applecart</summary>
			<starRating>5</starRating>
		*/
		
				// Writing XML
				$h = fopen($dir.str_replace(".".$ext,".xml", $file),"w");
				fwrite($h, $xml);
				fclose($h);
			}
			echo "\t";
			if(file_exists($dir."cover.jpg")){ echo "1"; } else { echo "3"; }


			// Subtitles
			if(isset($argv[3]) and ($argv[3] == "1")){
				$suburl = "http://www.podnapisi.net/index.php/ppodnapisi/search?tbsl=3&sK=".$title."&sJ=".$thelanguage."&sT=1&sTS=".$season."&sTE=".$episode; 
$dbg = fopen("/tmp/subtitles.log","w");
fwrite($dbg,$suburl);
				$subfile = implode("",file($suburl));

fwrite($dbg,$subfile);

				$fileparts = array();
				preg_match_all("/download\?i\=(\d+)\".+?<div align=\"left\">Release: (.+?)<\/div>/",$subfile,$fileparts);
fwrite($dbg,print_r($fileparts,1));
				for($i=0;$i<count($fileparts[0]);$i++){
					$fndparts = preg_split("/[\W\_]/", strtolower($fileparts[2][$i]));
					$relparts = preg_split("/[\W\_]/", strtolower($release));

					if(count(array_diff($fndparts, $relparts)) < count($fndparts)/2){
						$srtfile = implode("",file("http://www.podnapisi.net/index.php/ppodnapisi/download?i=".$fileparts[1][$i]));
fwrite($dbg,"http://www.podnapisi.net/index.php/ppodnapisi/download?i=".$fileparts[1][$i]);
						$h = fopen("/tmp/seriesub.zip","w");
						fwrite($h, $srtfile);
						$zip = array();
						exec("unzip -nj /tmp/seriesub.zip -d /tmp/", $zip);
						foreach($zip as $zfile){
							$matches = array();
							if(preg_match("/inflating\:\s*(.+?\.srt)/", $zfile, $matches)){
								exec("cp '".$matches[1]."' '".$dir.str_replace(".".$ext,".srt", $file)."'");
								exec("rm '".$matches[1]."'");
								exec("rm /tmp/seriesub.zip");
								echo "\t1";
								break 2;
							}elseif(preg_match("/inflating\:\s*(.+?\.txt)/", $zfile, $matches)){
									exec("cp '".$matches[1]."' '".$dir.str_replace(".".$ext,".txt", $file)."'");
									exec("rm '".$matches[1]."'");
									exec("rm /tmp/seriesub.zip");
									echo "\t1";
									break 2;
							}
						}
					}else{
//						echo $fileparts[2][$i]." does not fit ".$release."\n";
					}
				}
			}
		}
	exit;



function get_show($show,$exact="",$episode="") {

if ( !$show ) { return FALSE; }

if ( $fp = fopen("http://www.tvrage.com/quickinfo.php?show=".urlencode($show)."&ep=".urlencode($episode)."&exact=".urlencode($exact),"r") )
  {
  while ( !feof($fp))
    {
    $line = fgets($fp,1024);
    list ($sec,$val) = explode('@',$line,2);
    if ($sec == "Show Name" )
      {
      $ret[0] = $val;
      }
    elseif ( $sec == "Show URL" )
      {
      $ret[1] = $val;
      }
    elseif ( $sec == "Premiered" )
      {
      $ret[2] = $val;
      }
    elseif ($sec == "Country" )
      {
      $ret[7] = $val;
      }
    elseif ( $sec == "Status" )
      {
      $ret[8] = $val;
      }
    elseif ( $sec == "Classification" )
      {
      $ret[9] = $val;
      }
    elseif ( $sec == "Genres" )
      {
      $ret[10] = $val;
      }
    elseif ( $sec == "Network" )
      {
      $ret[11] = $val;
      }
    elseif ( $sec == "Airtime" )
      {
      $ret[12] = $val;
      }

    elseif ( $sec == "Latest Episode" )
      {
      list ($ep,$title,$airdate) = explode('^',$val);
      $ret[3] = $ep.", \"".$title."\" aired on ".$airdate;
      }
    elseif ( $sec == "Next Episode" )
      {
      list ($ep,$title,$airdate) = explode('^',$val);
      $ret[4] = $ep.", \"".$title."\" airs on ".$airdate;
      }
    elseif ( $sec == "Episode Info" )
      {
      list ($ep,$title,$airdate) = explode('^',$val);
      $ret[5] = $ep.", \"".$title."\" aired on ".$airdate;
      }
    elseif ( $sec == "Episode URL" )
      {
      $ret[6] = $val;
      }
    }
  fclose($fp);
  if ( $ret[0] )
    {
    return $ret;
    }
  }
else
  {
  return FALSE;
  }
}


?>
